<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-30 12:48:32
 * Desc:
 */

namespace app\base\model\user;

use think\Model;

class UserFriend extends Model
{

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = false;

    protected $table = 'xy_user.xy_user_friend';

    const SOURCE_MINI_INVITE = 'mini_invite';//小程序邀请注册
    const SOURCE_MINI_SUPPORT_WISH = 'mini_support_wish';//小程序支持心愿
    const SOURCE_MINI_BE_SUPPORT_WISH = 'mini_be_support_wish';//小程序被支持心愿
    const SOURCE_MINI_INVITE_ACCESS_WISH = 'mini_invite_access_wish';//小程序邀请访问心愿详情
    const SOURCE_MINI_BE_INVITE_ACCESS_WISH = 'mini_be_invite_access_wish';//小程序邀请访问心愿详情

    /**
     * Desc: 邀请，绑定好友关系，此方法仅限用户注册时使用
     * Date: 2020/2/19 20:15
     * Author: yiyu
     * @param $user_id
     * @param $refer_code
     * @param $source
     * @return UserFriend|bool
     */
    public static function bindFriendByReferCode($user_id, $refer_code, $source)
    {
        $refer_user_id = User::getUserIdByReferCode($refer_code);
        if ($refer_user_id && $refer_user_id != $user_id) {
            $friend_info = self::where('user_id', $user_id)->where('friend_user_id', $refer_user_id)->find();
            //邀请数量+1
            UserStatisticsInfo::userStatistics($refer_user_id, 'refer_people_num');
            if (empty($friend_info)) {
                return self::create([
                    'user_id' => $user_id,
                    'friend_user_id' => $refer_user_id,
                    'friend_source' => $source,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }

            $be_friend_info = self::where('user_id', $refer_user_id)->where('friend_user_id', $user_id)->find();
            if (empty($be_friend_info)) {
                return self::create([
                    'user_id' => $refer_user_id,
                    'friend_user_id' => $user_id,
                    'friend_source' => $source,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
        }

        return false;
    }

    public static function bindFriendByFriendUserId($user_id, $friend_user_id, $source)
    {
        if ($friend_user_id != $user_id) {
            $friend_info = self::where('user_id', $user_id)->where('friend_user_id', $friend_user_id)->find();
            if (empty($friend_info)) {
                return self::create([
                    'user_id' => $user_id,
                    'friend_user_id' => $friend_user_id,
                    'friend_source' => $source,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
        }

        return false;
    }

    public static function getMyFriend($user_id)
    {
        return self::where('user_id', $user_id)->column('friend_user_id');
    }

}